package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResultByReturnOrderDetail;
import com.jixi.common.result.Result;
import com.jixi.common.utils.ListToStringUtil;
import com.jixi.mapper.*;
import com.jixi.pojo.dto.ReturnDownloadDto;
import com.jixi.pojo.entity.*;
import com.jixi.pojo.vo.ReturnOrderDetailListVO;
import com.jixi.pojo.vo.ReturnOrderMonthDownloadVo;
import com.jixi.service.ReturnOrderDetailService;
import jakarta.servlet.http.HttpServletResponse;
import org.burningwave.core.assembler.StaticComponentContainer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReturnOrderDetailServiceImpl extends ServiceImpl<ReturnOrderDetailMapper, ReturnOrderDetail> implements ReturnOrderDetailService {
	
	@Autowired
	private ReturnOrderDetailMapper returnOrderDetailMapper;
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private OrderDailyMapper orderDailyMapper;
	
	@Autowired
	private SchoolMapper schoolMapper;
	
	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private SetmealMapper setmealMapper;
	
	/**
	 * 退餐订单列表
	 *
	 * @param pageNum        页码
	 * @param pageSize       每页数量
	 * @param returnNumber   退餐订单编号
	 * @param companyId      餐饮公司id
	 * @param schoolId       学校id
	 * @param bankCardHolder 接收退款的银行卡持卡人姓名
	 * @param cardNumber     接收退款的银行卡号
	 * @param returnStatus   退餐订单状态
	 * @param timeValue      时间（月）
	 * @return 退餐订单列表
	 */
	@Override
	public Result<PageResultByReturnOrderDetail> returnOrderPage(
			Integer pageNum,
			Integer pageSize,
			String returnNumber,
			Long companyId,
			Long schoolId,
			String bankCardHolder,
			String cardNumber,
			Integer returnStatus,
			String timeValue
	) {
		//分页构造器
		Page<ReturnOrderDetail> pageInfo = new Page<>(pageNum, pageSize);
		
		//条件构造器
		LambdaQueryWrapper<ReturnOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(ReturnOrderDetail::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.like(returnNumber != null && ! returnNumber.trim().isEmpty(), ReturnOrderDetail::getReturnNumber, returnNumber);
		queryWrapper.eq(companyId != null, ReturnOrderDetail::getCompanyId, companyId);
		queryWrapper.eq(schoolId != null, ReturnOrderDetail::getSchoolId, schoolId);
		queryWrapper.like(bankCardHolder != null && ! bankCardHolder.trim().isEmpty(), ReturnOrderDetail::getBankCardHolder, bankCardHolder);
		queryWrapper.like(cardNumber != null && ! cardNumber.trim().isEmpty(), ReturnOrderDetail::getCardNumber, cardNumber);
		queryWrapper.eq(returnStatus != null, ReturnOrderDetail::getReturnStatus, returnStatus);
		queryWrapper.like(timeValue != null && ! timeValue.trim().isEmpty(), ReturnOrderDetail::getReturnDate, timeValue);
		//根据创建时间降序排序
		queryWrapper.orderByDesc(ReturnOrderDetail::getCreateTime);
		
		//执行分页查询
		returnOrderDetailMapper.selectPage(pageInfo, queryWrapper);
		
		//处理名字信息
		List<ReturnOrderDetailListVO> returnOrderDetailList = pageInfo.getRecords().stream()
				.map(returnOrderDetail -> {
					ReturnOrderDetailListVO vo = new ReturnOrderDetailListVO();
					BeanUtils.copyProperties(returnOrderDetail, vo); //使用Spring的Bean工具类复制属性
					
					Long setmealId1 = vo.getSetmealId();
					Setmeal setmeal = setmealMapper.selectById(setmealId1);
					if (setmeal == null || setmeal.getIsDeleted() == 1) {
						vo.setSetmealName("该套餐不存在");
					} else if (setmeal.getStatus() == 0) {
						vo.setSetmealName(setmeal.getSetmealName() + "（该套餐已停售）");
					}
					else {
						vo.setSetmealName(setmeal.getSetmealName());
					}
					
					Long schoolId1 = vo.getSchoolId();
					School school = schoolMapper.selectById(schoolId1);
					if (school == null || school.getIsDeleted() == 1) {
						vo.setSchoolName("该学校不存在");
					} else if (school.getStatus() == 0) {
						vo.setSchoolName(school.getSchoolName() + "（该学校已停用）");
					} else {
						vo.setSchoolName(school.getSchoolName());
					}
					
					Long companyId1 = vo.getCompanyId();
					Company company = companyMapper.selectById(companyId1);
					if (company == null || company.getIsDeleted() == 1) {
						vo.setCompanyName("该餐饮公司不存在");
					} else if (company.getStatus() == 0) {
						vo.setCompanyName(company.getCompanyName() + "（该餐饮公司已停用）");
					} else {
						vo.setCompanyName(company.getCompanyName());
					}
					
					return vo;
				}).collect(Collectors.toList());
		
		//统计符合条件的退餐订单的总计金额
		List<ReturnOrderDetail> returnOrderList = returnOrderDetailMapper.selectList(queryWrapper);
		Double totalMoney = 0.0;
		for(ReturnOrderDetail returnOrder : returnOrderList){
			totalMoney += returnOrder.getTotalAmount();
		}
		
		//处理分页信息
		PageResultByReturnOrderDetail pageResult = new PageResultByReturnOrderDetail(pageInfo.getTotal(), returnOrderDetailList, totalMoney);
		return Result.success(pageResult);
	}
	
	/**
	 * 退餐订单详情
	 *
	 * @param returnDetailId 退餐订单id
	 * @return 退餐订单详情
	 */
	@Override
	public ReturnOrderDetail getReturnOrderInfoById(Long returnDetailId) {
		//只查未删除的
		LambdaQueryWrapper<ReturnOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ReturnOrderDetail::getIsDeleted, 0);
		queryWrapper.eq(ReturnOrderDetail::getReturnDetailId, returnDetailId);
		ReturnOrderDetail returnOrderDetail = returnOrderDetailMapper.selectOne(queryWrapper);
		return returnOrderDetail;
	}
	
	/**
	 * 统计退餐订单数量
	 *
	 * @return 退餐订单数量
	 */
	@Override
	public Long countReturnOrder() {
		LambdaQueryWrapper<ReturnOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ReturnOrderDetail::getIsDeleted, 0);
		return returnOrderDetailMapper.selectCount(queryWrapper);
	}
	
	/**
	 * 导出退餐订单明细统计excel
	 */
	@Override
	public void downloadReturnOrder(HttpServletResponse response, ReturnDownloadDto returnDownloadDto) throws IOException {
		//查询列表
		List<ReturnOrderMonthDownloadVo> list = returnOrderDetailMapper.getMonthReturnOrderDownLoad(returnDownloadDto);
		/*String EXCEL_NAME = "搜索条件：";
		int flag_name = 0;
		
		if(returnDownloadDto.getReturnNumber() != null && ! returnDownloadDto.getReturnNumber().trim().isEmpty()){
			EXCEL_NAME += " 退餐订单编号：" + returnDownloadDto.getReturnNumber();
			flag_name++;
		}
		if(returnDownloadDto.getSchoolId() != null){
			School school = schoolMapper.selectById(returnDownloadDto.getSchoolId());
			EXCEL_NAME += " 学校名称：" + school.getSchoolName();
			flag_name++;
		}
		if(returnDownloadDto.getCompanyId() != null){
			Company company = companyMapper.selectById(returnDownloadDto.getCompanyId());
			EXCEL_NAME += " 餐饮公司名称：" + company.getCompanyName();
			flag_name++;
		}
		if(returnDownloadDto.getBankCardHolder() != null && ! returnDownloadDto.getBankCardHolder().trim().isEmpty()){
			EXCEL_NAME += " 持卡人姓名：" + returnDownloadDto.getBankCardHolder();
			flag_name++;
		}
		if(returnDownloadDto.getCardNumber() != null && ! returnDownloadDto.getCardNumber().trim().isEmpty()){
			EXCEL_NAME += " 银行卡号：" + returnDownloadDto.getCardNumber();
			flag_name++;
		}
		if(returnDownloadDto.getReturnStatus() != null){
			EXCEL_NAME += " 退餐订单状态：" + returnDownloadDto.getReturnStatus();
			flag_name++;
		}
		if(returnDownloadDto.getTimeValue() != null && ! returnDownloadDto.getTimeValue().trim().isEmpty()){
			EXCEL_NAME += " 退餐时间：" + returnDownloadDto.getTimeValue();
			flag_name++;
		}
		if(flag_name == 0){
			EXCEL_NAME += " 无搜索条件";
		}*/
		
		System.out.println(list);
		//excel下载
		StaticComponentContainer.Modules.exportAllToAll();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		/*String fileName = URLEncoder.encode("退餐订单明细（" + EXCEL_NAME + "）", "UTF-8").replaceAll("\\+", "%20");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), ReturnOrderMonthDownloadVo.class)
				.sheet("退餐订单明细（" + EXCEL_NAME + "）")
				.doWrite(list);*/
		String fileName = URLEncoder.encode("退餐订单明细", "UTF-8").replaceAll("\\+", "%20");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), ReturnOrderMonthDownloadVo.class)
				.sheet("退餐订单明细")
				.doWrite(list);
	}
	
	/**
	 * 单选/批量修改退餐订单退款状态
	 *
	 * @param returnDetailIds 退餐订单id（多选）
	 * @param refundStatus    退款状态
	 * @return 操作结果
	 */
	@Override
	public Result updateReturnOrderRefundStatus(List<Long> returnDetailIds, Integer refundStatus) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		if (returnDetailIds == null || returnDetailIds.isEmpty()) {
			return Result.fail("未选择退餐订单");
		}
		
		if (refundStatus != 1 && refundStatus != 2) {
			return Result.fail("状态值有误");
		}
		
		//查询订单，获取订单List
		LambdaQueryWrapper<ReturnOrderDetail> queryWrapperReturnOrderDetail = new LambdaQueryWrapper<>();
		queryWrapperReturnOrderDetail.eq(ReturnOrderDetail::getIsDeleted, 0);
		queryWrapperReturnOrderDetail.in(ReturnOrderDetail::getReturnDetailId, returnDetailIds);
		List<ReturnOrderDetail> returnOrderDetailList = returnOrderDetailMapper.selectList(queryWrapperReturnOrderDetail);
		
		//遍历退餐订单List找到对应的日订餐订单，同时查status（不能是1已退款）
		List<OrderDaily> orderDailyList = new ArrayList<>();
		for (ReturnOrderDetail returnOrderDetail : returnOrderDetailList) {
			if (returnOrderDetail.getReturnStatus() == 1) {
				return Result.fail("存在已退款订单，请重新选择");
			}
			String orderNumber = returnOrderDetail.getOrderNumber();
			List<String> orderDateList = ListToStringUtil.convertJsonToList(returnOrderDetail.getReturnDate());
			LambdaQueryWrapper<OrderDaily> queryWrapperOrderDaily = new LambdaQueryWrapper<>();
			queryWrapperOrderDaily.eq(OrderDaily::getIsDeleted, 0);
			queryWrapperOrderDaily.eq(OrderDaily::getOrderNumber, orderNumber);
			queryWrapperOrderDaily.in(OrderDaily::getOrderDate, orderDateList);
			orderDailyList.addAll(orderDailyMapper.selectList(queryWrapperOrderDaily));
		}
		
		//修改退款状态
		for(ReturnOrderDetail returnOrderDetail : returnOrderDetailList){
			returnOrderDetail.setReturnStatus(refundStatus);
			returnOrderDetail.setUpdateTime(DateTime.now());
			returnOrderDetailMapper.updateById(returnOrderDetail);
		}
		//对于退餐订单，1=退款成功，2=退款失败
		//对于日订餐订单，3=退款成功，4=退款失败
		for(OrderDaily orderDaily : orderDailyList){
			orderDaily.setOrderDateStatus(refundStatus + 2);
			orderDaily.setUpdateTime(DateTime.now());
			orderDailyMapper.updateById(orderDaily);
		}
		
		return Result.success(returnOrderDetailList.size() + " 条退餐订单的退款状态修改成功");
	}
}
